package com.campusbackend.service.impl;

import com.campusbackend.entity.Students;
import com.campusbackend.entity.Teachers;
import com.campusbackend.entity.vo.PendingAuditUserVO;
import com.campusbackend.entity.vo.UserAuditRequestVO;
import com.campusbackend.entity.vo.UserStatisticsVO;
import com.campusbackend.entity.vo.UserManagementVO;
import com.campusbackend.entity.vo.UserSearchRequestVO;
import com.campusbackend.entity.vo.UserDetailVO;
import com.campusbackend.entity.vo.UserUpdateRequestVO;
import com.campusbackend.entity.vo.DailyUserStatisticsVO;
import com.campusbackend.mapper.StudentsMapper;
import com.campusbackend.mapper.TeachersMapper;
import com.campusbackend.service.UserAuditService;
import com.campusbackend.service.StudentSkillsService;
import com.campusbackend.service.SkillsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 用户审核服务实现类
 * 
 * @author yezi
 * @since 2025-07-27
 */
@Slf4j
@Service
public class UserAuditServiceImpl implements UserAuditService {

    @Autowired
    private TeachersMapper teachersMapper;

    @Autowired
    private StudentsMapper studentsMapper;

    @Autowired
    private StudentSkillsService studentSkillsService;

    @Autowired
    private SkillsService skillsService;

    @Override
    public List<PendingAuditUserVO> getPendingAuditUsers() {
        List<PendingAuditUserVO> result = new ArrayList<>();
        
        try {
            // 获取待审核教师
            List<Teachers> pendingTeachers = teachersMapper.getPendingAuditTeachers();
            for (Teachers teacher : pendingTeachers) {
                PendingAuditUserVO vo = new PendingAuditUserVO();
                vo.setId(teacher.getId());
                vo.setUserType(1); // 教师
                vo.setUserTypeName("教师");
                vo.setLoginId(teacher.getEmployeeId());
                vo.setRealName(teacher.getRealName());
                vo.setPhone(teacher.getPhone());
                vo.setEmail(teacher.getEmail());
                vo.setProfessionalTitle(teacher.getProfessionalTitle());
                vo.setIdCard(teacher.getIdCard());
                vo.setAuditStatus(teacher.getAuditStatus());
                vo.setAuditReason(teacher.getAuditReason());
                vo.setAuditTime(teacher.getAuditTime());
                vo.setCreateTime(teacher.getCreateTime());
                result.add(vo);
            }
            
            // 获取待审核学生
            List<Students> pendingStudents = studentsMapper.getPendingAuditStudents();
            for (Students student : pendingStudents) {
                PendingAuditUserVO vo = new PendingAuditUserVO();
                vo.setId(student.getId());
                vo.setUserType(2); // 学生
                vo.setUserTypeName("学生");
                vo.setLoginId(student.getStudentId());
                vo.setRealName(student.getRealName());
                vo.setEmail(student.getEmail());
                vo.setCollege(student.getCollege());
                vo.setAuditStatus(student.getAuditStatus());
                vo.setAuditReason(student.getAuditReason());
                vo.setAuditTime(student.getAuditTime());
                vo.setCreateTime(student.getCreateTime());
                result.add(vo);
            }
            
            // 按创建时间倒序排列
            result.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
            
        } catch (Exception e) {
            log.error("获取待审核用户列表异常", e);
        }
        
        return result;
    }

    @Override
    @Transactional
    public String auditUser(UserAuditRequestVO auditRequest) {
        try {
            Byte auditStatus = Byte.valueOf(auditRequest.getAuditStatus());

            if (auditRequest.getUserType() == 1) {
                // 审核教师
                int result;
                if (auditStatus == 1) {
                    // 审核通过：只更新审核状态，账号状态保持正常(1)
                    result = teachersMapper.updateAuditStatus(
                        auditRequest.getUserId(),
                        auditStatus,
                        auditRequest.getAuditReason()
                    );
                } else {
                    // 审核驳回：同时更新审核状态为驳回(2)，账号状态为禁用(0)
                    result = teachersMapper.updateAuditAndAccountStatus(
                        auditRequest.getUserId(),
                        auditStatus,  // 审核状态：2-驳回
                        (byte) 0,     // 账号状态：0-禁用
                        auditRequest.getAuditReason()
                    );
                }

                if (result > 0) {
                    String statusText = auditStatus == 1 ? "通过" : "拒绝";
                    String accountStatusText = auditStatus == 1 ? "" : "，账号已禁用";
                    log.info("教师审核成功 - userId: {}, auditStatus: {}, accountStatus: {}",
                        auditRequest.getUserId(), statusText, auditStatus == 1 ? "正常" : "禁用");
                    return "审核" + statusText + "成功" + accountStatusText;
                } else {
                    return "审核失败，教师不存在或状态异常";
                }

            } else if (auditRequest.getUserType() == 2) {
                // 审核学生
                int result;
                if (auditStatus == 1) {
                    // 审核通过：只更新审核状态，账号状态保持正常(1)
                    result = studentsMapper.updateAuditStatus(
                        auditRequest.getUserId(),
                        auditStatus,
                        auditRequest.getAuditReason()
                    );
                } else {
                    // 审核驳回：同时更新审核状态为驳回(2)，账号状态为禁用(0)
                    result = studentsMapper.updateAuditAndAccountStatus(
                        auditRequest.getUserId(),
                        auditStatus,  // 审核状态：2-驳回
                        (byte) 0,     // 账号状态：0-禁用
                        auditRequest.getAuditReason()
                    );
                }

                if (result > 0) {
                    String statusText = auditStatus == 1 ? "通过" : "拒绝";
                    String accountStatusText = auditStatus == 1 ? "" : "，账号已禁用";
                    log.info("学生审核成功 - userId: {}, auditStatus: {}, accountStatus: {}",
                        auditRequest.getUserId(), statusText, auditStatus == 1 ? "正常" : "禁用");
                    return "审核" + statusText + "成功" + accountStatusText;
                } else {
                    return "审核失败，学生不存在或状态异常";
                }

            } else {
                return "无效的用户类型";
            }

        } catch (Exception e) {
            log.error("审核用户异常", e);
            return "审核过程中发生错误，请稍后重试";
        }
    }

    @Override
    public UserStatisticsVO getUserStatistics() {
        UserStatisticsVO statistics = new UserStatisticsVO();
        
        try {
            // 教师统计
            statistics.setTotalTeachers(teachersMapper.selectCount(null));
            statistics.setPendingTeachers(teachersMapper.countByAuditStatus((byte) 0));
            statistics.setApprovedTeachers(teachersMapper.countByAuditStatus((byte) 1));
            statistics.setRejectedTeachers(teachersMapper.countByAuditStatus((byte) 2));
            statistics.setDisabledTeachers(teachersMapper.countByStatus((byte) 0));
            statistics.setTodayNewTeachers(teachersMapper.countTodayNew());
            statistics.setMonthNewTeachers(teachersMapper.countMonthNew());
            
            // 学生统计
            statistics.setTotalStudents(studentsMapper.selectCount(null));
            statistics.setPendingStudents(studentsMapper.countByAuditStatus((byte) 0));
            statistics.setApprovedStudents(studentsMapper.countByAuditStatus((byte) 1));
            statistics.setRejectedStudents(studentsMapper.countByAuditStatus((byte) 2));
            statistics.setDisabledStudents(studentsMapper.countByStatus((byte) 0));
            statistics.setTodayNewStudents(studentsMapper.countTodayNew());
            statistics.setMonthNewStudents(studentsMapper.countMonthNew());
            
        } catch (Exception e) {
            log.error("获取用户统计信息异常", e);
        }
        
        return statistics;
    }

    @Override
    public List<UserManagementVO> getAllTeachers() {
        List<UserManagementVO> result = new ArrayList<>();
        
        try {
            List<Teachers> teachers = teachersMapper.getAllTeachersForManagement();
            for (Teachers teacher : teachers) {
                UserManagementVO vo = new UserManagementVO();
                vo.setId(teacher.getId());
                vo.setUserType(1);
                vo.setUserTypeName("教师");
                vo.setLoginId(teacher.getEmployeeId());
                vo.setRealName(teacher.getRealName());
                vo.setPhone(teacher.getPhone());
                vo.setEmail(teacher.getEmail());
                vo.setProfessionalTitle(teacher.getProfessionalTitle());
                vo.setAuditStatus(teacher.getAuditStatus());
                vo.setAuditStatusName(getAuditStatusName(teacher.getAuditStatus()));
                vo.setStatus(teacher.getStatus());
                vo.setStatusName(getStatusName(teacher.getStatus()));
                vo.setCreateTime(teacher.getCreateTime());
                vo.setUpdateTime(teacher.getUpdateTime());
                result.add(vo);
            }
        } catch (Exception e) {
            log.error("获取教师列表异常", e);
        }
        
        return result;
    }

    @Override
    public List<UserManagementVO> getAllStudents() {
        List<UserManagementVO> result = new ArrayList<>();
        
        try {
            List<Students> students = studentsMapper.getAllStudentsForManagement();
            for (Students student : students) {
                UserManagementVO vo = new UserManagementVO();
                vo.setId(student.getId());
                vo.setUserType(2);
                vo.setUserTypeName("学生");
                vo.setLoginId(student.getStudentId());
                vo.setRealName(student.getRealName());
                vo.setEmail(student.getEmail());
                vo.setCollege(student.getCollege());
                vo.setAge(student.getAge());
                vo.setAuditStatus(student.getAuditStatus());
                vo.setAuditStatusName(getAuditStatusName(student.getAuditStatus()));
                vo.setStatus(student.getStatus());
                vo.setStatusName(getStatusName(student.getStatus()));
                vo.setCreateTime(student.getCreateTime());
                vo.setUpdateTime(student.getUpdateTime());
                result.add(vo);
            }
        } catch (Exception e) {
            log.error("获取学生列表异常", e);
        }
        
        return result;
    }

    @Override
    @Transactional
    public String deactivateUser(Long userId, Integer userType) {
        try {
            if (userType == 1) {
                // 禁用教师
                Teachers teacher = teachersMapper.selectById(userId);
                if (teacher == null) {
                    return "教师不存在";
                }
                
                teacher.setStatus((byte) 0);
                int result = teachersMapper.updateById(teacher);
                
                if (result > 0) {
                    log.info("教师账号禁用成功 - userId: {}", userId);
                    return "教师账号禁用成功";
                } else {
                    return "教师账号禁用失败";
                }
                
            } else if (userType == 2) {
                // 禁用学生
                Students student = studentsMapper.selectById(userId);
                if (student == null) {
                    return "学生不存在";
                }
                
                student.setStatus((byte) 0);
                int result = studentsMapper.updateById(student);
                
                if (result > 0) {
                    log.info("学生账号禁用成功 - userId: {}", userId);
                    return "学生账号禁用成功";
                } else {
                    return "学生账号禁用失败";
                }
                
            } else {
                return "无效的用户类型";
            }
            
        } catch (Exception e) {
            log.error("禁用用户异常", e);
            return "禁用过程中发生错误，请稍后重试";
        }
    }

    @Override
    @Transactional
    public String activateUser(Long userId, Integer userType) {
        try {
            if (userType == 1) {
                // 启用教师
                Teachers teacher = teachersMapper.selectById(userId);
                if (teacher == null) {
                    return "教师不存在";
                }
                
                teacher.setStatus((byte) 1);
                int result = teachersMapper.updateById(teacher);
                
                if (result > 0) {
                    log.info("教师账号启用成功 - userId: {}", userId);
                    return "教师账号启用成功";
                } else {
                    return "教师账号启用失败";
                }
                
            } else if (userType == 2) {
                // 启用学生
                Students student = studentsMapper.selectById(userId);
                if (student == null) {
                    return "学生不存在";
                }
                
                student.setStatus((byte) 1);
                int result = studentsMapper.updateById(student);
                
                if (result > 0) {
                    log.info("学生账号启用成功 - userId: {}", userId);
                    return "学生账号启用成功";
                } else {
                    return "学生账号启用失败";
                }
                
            } else {
                return "无效的用户类型";
            }
            
        } catch (Exception e) {
            log.error("启用用户异常", e);
            return "启用过程中发生错误，请稍后重试";
        }
    }

    /**
     * 获取审核状态名称
     */
    private String getAuditStatusName(Byte auditStatus) {
        if (auditStatus == null) return "未知";
        switch (auditStatus) {
            case 0: return "待审核";
            case 1: return "审核通过";
            case 2: return "审核拒绝";
            default: return "未知";
        }
    }

    /**
     * 获取账号状态名称
     */
    private String getStatusName(Byte status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "禁用";
            case 1: return "正常";
            default: return "未知";
        }
    }

    @Override
    public List<PendingAuditUserVO> getRejectedUsers() {
        List<PendingAuditUserVO> result = new ArrayList<>();

        try {
            // 获取被驳回教师
            List<Teachers> rejectedTeachers = teachersMapper.getRejectedTeachers();
            for (Teachers teacher : rejectedTeachers) {
                PendingAuditUserVO vo = new PendingAuditUserVO();
                vo.setId(teacher.getId());
                vo.setUserType(1);
                vo.setUserTypeName("教师");
                vo.setLoginId(teacher.getEmployeeId());
                vo.setRealName(teacher.getRealName());
                vo.setPhone(teacher.getPhone());
                vo.setEmail(teacher.getEmail());
                vo.setProfessionalTitle(teacher.getProfessionalTitle());
                vo.setIdCard(teacher.getIdCard());
                vo.setAuditStatus(teacher.getAuditStatus());
                vo.setAuditReason(teacher.getAuditReason());
                vo.setAuditTime(teacher.getAuditTime());
                vo.setCreateTime(teacher.getCreateTime());
                result.add(vo);
            }

            // 获取被驳回学生
            List<Students> rejectedStudents = studentsMapper.getRejectedStudents();
            for (Students student : rejectedStudents) {
                PendingAuditUserVO vo = new PendingAuditUserVO();
                vo.setId(student.getId());
                vo.setUserType(2);
                vo.setUserTypeName("学生");
                vo.setLoginId(student.getStudentId());
                vo.setRealName(student.getRealName());
                vo.setEmail(student.getEmail());
                vo.setCollege(student.getCollege());
                vo.setAuditStatus(student.getAuditStatus());
                vo.setAuditReason(student.getAuditReason());
                vo.setAuditTime(student.getAuditTime());
                vo.setCreateTime(student.getCreateTime());
                result.add(vo);
            }

            // 按审核时间倒序排列
            result.sort((a, b) -> {
                if (a.getAuditTime() == null && b.getAuditTime() == null) return 0;
                if (a.getAuditTime() == null) return 1;
                if (b.getAuditTime() == null) return -1;
                return b.getAuditTime().compareTo(a.getAuditTime());
            });

        } catch (Exception e) {
            log.error("获取被驳回用户列表异常", e);
        }

        return result;
    }

    @Override
    public List<UserManagementVO> getDeactivatedUsers() {
        List<UserManagementVO> result = new ArrayList<>();

        try {
            // 获取被注销教师
            List<Teachers> deactivatedTeachers = teachersMapper.getDeactivatedTeachers();
            for (Teachers teacher : deactivatedTeachers) {
                UserManagementVO vo = new UserManagementVO();
                vo.setId(teacher.getId());
                vo.setUserType(1);
                vo.setUserTypeName("教师");
                vo.setLoginId(teacher.getEmployeeId());
                vo.setRealName(teacher.getRealName());
                vo.setPhone(teacher.getPhone());
                vo.setEmail(teacher.getEmail());
                vo.setProfessionalTitle(teacher.getProfessionalTitle());
                vo.setAuditStatus(teacher.getAuditStatus());
                vo.setAuditStatusName(getAuditStatusName(teacher.getAuditStatus()));
                vo.setStatus(teacher.getStatus());
                vo.setStatusName(getStatusName(teacher.getStatus()));
                vo.setCreateTime(teacher.getCreateTime());
                vo.setUpdateTime(teacher.getUpdateTime());
                result.add(vo);
            }

            // 获取被注销学生
            List<Students> deactivatedStudents = studentsMapper.getDeactivatedStudents();
            for (Students student : deactivatedStudents) {
                UserManagementVO vo = new UserManagementVO();
                vo.setId(student.getId());
                vo.setUserType(2);
                vo.setUserTypeName("学生");
                vo.setLoginId(student.getStudentId());
                vo.setRealName(student.getRealName());
                vo.setEmail(student.getEmail());
                vo.setCollege(student.getCollege());
                vo.setAge(student.getAge());
                vo.setAuditStatus(student.getAuditStatus());
                vo.setAuditStatusName(getAuditStatusName(student.getAuditStatus()));
                vo.setStatus(student.getStatus());
                vo.setStatusName(getStatusName(student.getStatus()));
                vo.setCreateTime(student.getCreateTime());
                vo.setUpdateTime(student.getUpdateTime());
                result.add(vo);
            }

            // 按更新时间倒序排列
            result.sort((a, b) -> {
                if (a.getUpdateTime() == null && b.getUpdateTime() == null) return 0;
                if (a.getUpdateTime() == null) return 1;
                if (b.getUpdateTime() == null) return -1;
                return b.getUpdateTime().compareTo(a.getUpdateTime());
            });

        } catch (Exception e) {
            log.error("获取被注销用户列表异常", e);
        }

        return result;
    }

    @Override
    public List<UserManagementVO> searchUsers(UserSearchRequestVO searchRequest) {
        List<UserManagementVO> result = new ArrayList<>();

        try {
            // 搜索教师
            if (searchRequest.getUserType() == null || searchRequest.getUserType() == 1) {
                List<Teachers> teachers = teachersMapper.searchTeachersForManagement(searchRequest.getKeyword());
                for (Teachers teacher : teachers) {
                    UserManagementVO vo = new UserManagementVO();
                    vo.setId(teacher.getId());
                    vo.setUserType(1);
                    vo.setUserTypeName("教师");
                    vo.setLoginId(teacher.getEmployeeId());
                    vo.setRealName(teacher.getRealName());
                    vo.setPhone(teacher.getPhone());
                    vo.setEmail(teacher.getEmail());
                    vo.setProfessionalTitle(teacher.getProfessionalTitle());
                    vo.setAuditStatus(teacher.getAuditStatus());
                    vo.setAuditStatusName(getAuditStatusName(teacher.getAuditStatus()));
                    vo.setStatus(teacher.getStatus());
                    vo.setStatusName(getStatusName(teacher.getStatus()));
                    vo.setCreateTime(teacher.getCreateTime());
                    vo.setUpdateTime(teacher.getUpdateTime());
                    result.add(vo);
                }
            }

            // 搜索学生
            if (searchRequest.getUserType() == null || searchRequest.getUserType() == 2) {
                List<Students> students = studentsMapper.searchStudentsForManagement(searchRequest.getKeyword());
                for (Students student : students) {
                    UserManagementVO vo = new UserManagementVO();
                    vo.setId(student.getId());
                    vo.setUserType(2);
                    vo.setUserTypeName("学生");
                    vo.setLoginId(student.getStudentId());
                    vo.setRealName(student.getRealName());
                    vo.setEmail(student.getEmail());
                    vo.setCollege(student.getCollege());
                    vo.setAge(student.getAge());
                    vo.setAuditStatus(student.getAuditStatus());
                    vo.setAuditStatusName(getAuditStatusName(student.getAuditStatus()));
                    vo.setStatus(student.getStatus());
                    vo.setStatusName(getStatusName(student.getStatus()));
                    vo.setCreateTime(student.getCreateTime());
                    vo.setUpdateTime(student.getUpdateTime());
                    result.add(vo);
                }
            }

            // 按创建时间倒序排列
            result.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));

        } catch (Exception e) {
            log.error("搜索用户异常", e);
        }

        return result;
    }

    @Override
    public UserDetailVO getUserDetail(String loginId, Integer userType) {
        try {
            if (userType == 1) {
                // 获取教师详情
                Teachers teacher = teachersMapper.findByEmployeeIdForDetail(loginId);
                if (teacher == null) {
                    return null;
                }

                UserDetailVO vo = new UserDetailVO();
                vo.setId(teacher.getId());
                vo.setUserType(1);
                vo.setUserTypeName("教师");
                vo.setLoginId(teacher.getEmployeeId());
                vo.setUsername(teacher.getUsername());
                vo.setRealName(teacher.getRealName());
                vo.setPhone(teacher.getPhone());
                vo.setEmail(teacher.getEmail());
                vo.setProfessionalTitle(teacher.getProfessionalTitle());
                vo.setIdCard(teacher.getIdCard());
                vo.setAuditStatus(teacher.getAuditStatus());
                vo.setAuditStatusName(getAuditStatusName(teacher.getAuditStatus()));
                vo.setAuditReason(teacher.getAuditReason());
                vo.setAuditTime(teacher.getAuditTime());
                vo.setStatus(teacher.getStatus());
                vo.setStatusName(getStatusName(teacher.getStatus()));
                vo.setCreateTime(teacher.getCreateTime());
                vo.setUpdateTime(teacher.getUpdateTime());

                return vo;

            } else if (userType == 2) {
                // 获取学生详情
                Students student = studentsMapper.findByStudentIdForDetail(loginId);
                if (student == null) {
                    return null;
                }

                UserDetailVO vo = new UserDetailVO();
                vo.setId(student.getId());
                vo.setUserType(2);
                vo.setUserTypeName("学生");
                vo.setLoginId(student.getStudentId());
                vo.setUsername(student.getUsername());
                vo.setRealName(student.getRealName());
                vo.setEmail(student.getEmail());
                vo.setCollege(student.getCollege());
                vo.setAge(student.getAge());
                vo.setAuditStatus(student.getAuditStatus());
                vo.setAuditStatusName(getAuditStatusName(student.getAuditStatus()));
                vo.setAuditReason(student.getAuditReason());
                vo.setAuditTime(student.getAuditTime());
                vo.setStatus(student.getStatus());
                vo.setStatusName(getStatusName(student.getStatus()));
                vo.setCreateTime(student.getCreateTime());
                vo.setUpdateTime(student.getUpdateTime());

                // 获取学生技能
                try {
                    List<String> skills = studentSkillsService.getStudentSkillNames(student.getId());
                    vo.setSkills(skills);
                } catch (Exception e) {
                    log.warn("获取学生技能信息异常 - studentId: {}", student.getId(), e);
                }

                return vo;
            }

        } catch (Exception e) {
            log.error("获取用户详情异常 - loginId: {}, userType: {}", loginId, userType, e);
        }

        return null;
    }

    @Override
    @Transactional
    public String updateUser(UserUpdateRequestVO updateRequest) {
        try {
            if (updateRequest.getUserType() == 1) {
                // 更新教师信息
                Teachers teacher = teachersMapper.selectById(updateRequest.getId());
                if (teacher == null) {
                    return "教师不存在";
                }

                // 检查邮箱是否被其他教师占用
                if (!updateRequest.getEmail().equals(teacher.getEmail())) {
                    if (teachersMapper.countByEmailExcludeCurrentUser(updateRequest.getEmail(), teacher.getEmployeeId()) > 0) {
                        return "该邮箱已被其他教师使用";
                    }
                }

                // 检查手机号是否被其他教师占用
                if (updateRequest.getPhone() != null && !updateRequest.getPhone().equals(teacher.getPhone())) {
                    if (teachersMapper.countByPhoneExcludeCurrentUser(updateRequest.getPhone(), teacher.getEmployeeId()) > 0) {
                        return "该手机号已被其他教师使用";
                    }
                }

                // 检查身份证号是否被其他教师占用
                if (updateRequest.getIdCard() != null && !updateRequest.getIdCard().equals(teacher.getIdCard())) {
                    if (teachersMapper.countByIdCardExcludeCurrentUser(updateRequest.getIdCard(), teacher.getEmployeeId()) > 0) {
                        return "该身份证号已被其他教师使用";
                    }
                }

                // 更新教师信息
                teacher.setRealName(updateRequest.getRealName());
                teacher.setPhone(updateRequest.getPhone());
                teacher.setEmail(updateRequest.getEmail());
                teacher.setProfessionalTitle(updateRequest.getProfessionalTitle());
                teacher.setIdCard(updateRequest.getIdCard());

                int result = teachersMapper.updateById(teacher);
                if (result > 0) {
                    log.info("教师信息更新成功 - teacherId: {}", updateRequest.getId());
                    return "教师信息更新成功";
                } else {
                    return "教师信息更新失败";
                }

            } else if (updateRequest.getUserType() == 2) {
                // 更新学生信息
                Students student = studentsMapper.selectById(updateRequest.getId());
                if (student == null) {
                    return "学生不存在";
                }

                // 检查邮箱是否被其他学生占用
                if (!updateRequest.getEmail().equals(student.getEmail())) {
                    if (studentsMapper.countByEmailExcludeCurrentUser(updateRequest.getEmail(), student.getStudentId()) > 0) {
                        return "该邮箱已被其他学生使用";
                    }
                }

                // 更新学生信息
                student.setRealName(updateRequest.getRealName());
                student.setEmail(updateRequest.getEmail());
                student.setCollege(updateRequest.getCollege());
                student.setAge(updateRequest.getAge());

                int result = studentsMapper.updateById(student);
                if (result > 0) {
                    // 更新学生技能
                    List<Long> skillIds = null;

                    // 优先处理前端发送的技能名称数组
                    if (updateRequest.getSkills() != null && !updateRequest.getSkills().isEmpty()) {
                        try {
                            log.info("开始处理技能名称转换 - skills: {}", updateRequest.getSkills());
                            skillIds = skillsService.getSkillIdsByNames(updateRequest.getSkills());
                            log.info("技能名称转换为ID完成 - skills: {}, skillIds: {}", updateRequest.getSkills(), skillIds);

                            if (skillIds == null || skillIds.isEmpty()) {
                                log.warn("技能名称转换结果为空 - skills: {}", updateRequest.getSkills());
                            }
                        } catch (Exception e) {
                            log.error("技能名称转换为ID失败 - skills: {}", updateRequest.getSkills(), e);
                        }
                    }
                    // 如果没有技能名称，则使用技能ID（向后兼容）
                    else if (updateRequest.getSkillIds() != null && !updateRequest.getSkillIds().isEmpty()) {
                        skillIds = updateRequest.getSkillIds();
                    }

                    // 保存技能数据
                    if (skillIds != null && !skillIds.isEmpty()) {
                        boolean skillResult = studentSkillsService.updateStudentSkills(student.getId(), skillIds);
                        if (!skillResult) {
                            log.warn("学生技能更新失败 - studentId: {}, skillIds: {}", updateRequest.getId(), skillIds);
                        } else {
                            log.info("学生技能更新成功 - studentId: {}, skillIds: {}", updateRequest.getId(), skillIds);
                        }
                    } else {
                        log.info("没有技能数据需要更新 - studentId: {}", updateRequest.getId());
                    }

                    log.info("学生信息更新成功 - studentId: {}", updateRequest.getId());
                    return "学生信息更新成功";
                } else {
                    return "学生信息更新失败";
                }

            } else {
                return "无效的用户类型";
            }

        } catch (Exception e) {
            log.error("更新用户信息异常", e);
            return "更新过程中发生错误，请稍后重试";
        }
    }

    @Override
    public List<DailyUserStatisticsVO> getDailyUserStatistics(int days) {
        log.info("获取每日用户统计数据 - days: {}", days);

        try {
            // 获取教师每日统计数据
            List<Map<String, Object>> teacherStats = teachersMapper.getDailyNewTeachersCount(days);
            // 获取学生每日统计数据
            List<Map<String, Object>> studentStats = studentsMapper.getDailyNewStudentsCount(days);

            // 创建日期到统计数据的映射
            Map<String, DailyUserStatisticsVO> dateStatsMap = new HashMap<>();

            // 处理教师统计数据
            for (Map<String, Object> stat : teacherStats) {
                String date = stat.get("date").toString();
                Long count = Long.valueOf(stat.get("count").toString());

                DailyUserStatisticsVO dailyStat = dateStatsMap.getOrDefault(date, new DailyUserStatisticsVO());
                dailyStat.setDate(date);
                dailyStat.setNewTeachers(count);
                dailyStat.setNewStudents(dailyStat.getNewStudents() != null ? dailyStat.getNewStudents() : 0L);
                dateStatsMap.put(date, dailyStat);
            }

            // 处理学生统计数据
            for (Map<String, Object> stat : studentStats) {
                String date = stat.get("date").toString();
                Long count = Long.valueOf(stat.get("count").toString());

                DailyUserStatisticsVO dailyStat = dateStatsMap.getOrDefault(date, new DailyUserStatisticsVO());
                dailyStat.setDate(date);
                dailyStat.setNewStudents(count);
                dailyStat.setNewTeachers(dailyStat.getNewTeachers() != null ? dailyStat.getNewTeachers() : 0L);
                dateStatsMap.put(date, dailyStat);
            }

            // 填充缺失的日期（确保返回完整的天数）
            LocalDate endDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

            for (int i = 0; i < days; i++) {
                LocalDate currentDate = endDate.minusDays(i);
                String dateStr = currentDate.format(formatter);

                if (!dateStatsMap.containsKey(dateStr)) {
                    DailyUserStatisticsVO dailyStat = new DailyUserStatisticsVO();
                    dailyStat.setDate(dateStr);
                    dailyStat.setNewStudents(0L);
                    dailyStat.setNewTeachers(0L);
                    dateStatsMap.put(dateStr, dailyStat);
                }
            }

            // 转换为列表并计算总数
            List<DailyUserStatisticsVO> result = new ArrayList<>();
            for (int i = 0; i < days; i++) {
                LocalDate currentDate = endDate.minusDays(i);
                String dateStr = currentDate.format(formatter);

                DailyUserStatisticsVO dailyStat = dateStatsMap.get(dateStr);
                dailyStat.calculateTotalNew();
                result.add(dailyStat);
            }

            log.info("获取每日用户统计数据成功，返回{}条记录", result.size());
            return result;

        } catch (Exception e) {
            log.error("获取每日用户统计数据异常", e);
            return new ArrayList<>();
        }
    }

    /* ========== 数据导出方法实现 ========== */

    @Override
    public List<PendingAuditUserVO> getPendingAuditUsersForExport() {
        log.info("获取待审核用户数据用于导出");
        return getPendingAuditUsers();
    }

    @Override
    public List<PendingAuditUserVO> getRejectedUsersForExport() {
        log.info("获取被驳回用户数据用于导出");
        return getRejectedUsers();
    }

    @Override
    public List<UserManagementVO> getDeactivatedUsersForExport() {
        log.info("获取被注销用户数据用于导出");
        return getDeactivatedUsers();
    }

    @Override
    public List<UserManagementVO> getAllUsersForExport() {
        log.info("获取全部用户数据用于导出");
        List<UserManagementVO> result = new ArrayList<>();
        
        try {
            // 获取所有教师
            List<UserManagementVO> teachers = getAllTeachers();
            result.addAll(teachers);
            
            // 获取所有学生
            List<UserManagementVO> students = getAllStudents();
            result.addAll(students);
            
            // 按创建时间倒序排列
            result.sort((a, b) -> b.getCreateTime().compareTo(a.getCreateTime()));
            
            log.info("获取全部用户数据成功，共{}条记录", result.size());
            
        } catch (Exception e) {
            log.error("获取全部用户数据异常", e);
        }
        
        return result;
    }
}
